<?php
// 数据库配置
define('DB_NAME', 'vocabulary.db');

// 艾宾浩斯记忆曲线复习间隔（天）
$ebbinghaus_intervals = [0, 1, 2, 4, 7, 15];

// 初始化数据库
function init_db() {
    $db = new SQLite3(DB_NAME);
    
    // 创建词库表
    $db->exec("CREATE TABLE IF NOT EXISTS vocabulary (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        word TEXT NOT NULL UNIQUE,
        meaning TEXT NOT NULL,
        added_date DATE DEFAULT CURRENT_DATE
    )");
    
    // 创建学习进度表
    $db->exec("CREATE TABLE IF NOT EXISTS learning_progress (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        word_id INTEGER NOT NULL,
        review_date DATE NOT NULL,
        stage INTEGER DEFAULT 0,
        next_review_date DATE,
        status INTEGER DEFAULT 0,
        test_count INTEGER DEFAULT 0,
        correct_count INTEGER DEFAULT 0,
        FOREIGN KEY (word_id) REFERENCES vocabulary(id)
    )");
    
    // 创建错词表
    $db->exec("CREATE TABLE IF NOT EXISTS wrong_words (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        word_id INTEGER NOT NULL,
        test_date DATE DEFAULT CURRENT_DATE,
        FOREIGN KEY (word_id) REFERENCES vocabulary(id)
    )");
    
    // 创建用户设置表
    $db->exec("CREATE TABLE IF NOT EXISTS user_settings (
        id INTEGER PRIMARY KEY DEFAULT 1,
        daily_words INTEGER DEFAULT 20,
        last_study_date DATE,
        last_test_date DATE
    )");
    
    // 初始化设置
    $db->exec("INSERT OR IGNORE INTO user_settings (id, daily_words) VALUES (1, 20)");
    
    return $db;
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $db = init_db();
    
    // 导入词库
    if (isset($_FILES['vocab_file']) && $_FILES['vocab_file']['error'] == UPLOAD_ERR_OK) {
        // 检查是否清除现有词库
        if (isset($_POST['clear_existing'])) {
            $db->exec("DELETE FROM learning_progress");
            $db->exec("DELETE FROM wrong_words");
            $db->exec("DELETE FROM vocabulary");
        }
        
        $file = $_FILES['vocab_file']['tmp_name'];
        $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        
        foreach ($lines as $line) {
            list($word, $meaning) = explode(',', $line, 2);
            $word = trim($word);
            $meaning = trim($meaning);
            
            if (!empty($word) && !empty($meaning)) {
                $stmt = $db->prepare("INSERT OR IGNORE INTO vocabulary (word, meaning) VALUES (:word, :meaning)");
                $stmt->bindValue(':word', $word, SQLITE3_TEXT);
                $stmt->bindValue(':meaning', $meaning, SQLITE3_TEXT);
                $stmt->execute();
            }
        }
        
        // 重置最后学习日期
        $db->exec("UPDATE user_settings SET last_study_date = NULL WHERE id = 1");
    }
    
    // 更新每日学习单词数量
    if (isset($_POST['daily_words'])) {
        $dailyWords = (int)$_POST['daily_words'];
        $db->exec("UPDATE user_settings SET daily_words = $dailyWords WHERE id = 1");
    }
    
    // 处理测试答案
    if (isset($_POST['test_submit']) && isset($_POST['answers'])) {
        // 更新最后测试日期
        $db->exec("UPDATE user_settings SET last_test_date = CURRENT_DATE WHERE id = 1");
        
        foreach ($_POST['answers'] as $wordId => $answer) {
            $wordId = (int)$wordId;
            $answer = trim($answer);
            
            // 获取正确答案
            $correctAnswer = $db->querySingle("SELECT meaning FROM vocabulary WHERE id = $wordId");
            
            // 更新学习进度
            $db->exec("UPDATE learning_progress 
                       SET test_count = test_count + 1,
                       correct_count = correct_count + " . ($answer == $correctAnswer ? 1 : 0) . "
                       WHERE word_id = $wordId");
            
            // 如果答错，添加到错词表
            if ($answer != $correctAnswer) {
                $db->exec("INSERT INTO wrong_words (word_id) VALUES ($wordId)");
            }
            
            // 更新艾宾浩斯记忆阶段
            $progress = $db->querySingle("SELECT stage FROM learning_progress WHERE word_id = $wordId", true);
            $currentStage = $progress ? $progress['stage'] : 0;
            $newStage = min($currentStage + 1, count($ebbinghaus_intervals) - 1);
            $nextReview = date('Y-m-d', strtotime("+{$ebbinghaus_intervals[$newStage]} days"));
            
            $db->exec("UPDATE learning_progress 
                       SET stage = $newStage, next_review_date = '$nextReview'
                       WHERE word_id = $wordId");
            
            // 如果达到最高阶段，标记为已掌握
            if ($newStage == count($ebbinghaus_intervals) - 1) {
                $db->exec("UPDATE learning_progress SET status = 2 WHERE word_id = $wordId");
            }
        }
        
        // 提交后重定向到统计页面
        header("Location: ?page=statistics");
        exit;
    }
    
    $db->close();
}

// 获取当前页面
$page = isset($_GET['page']) ? $_GET['page'] : 'study';

// 初始化数据库连接
$db = init_db();

// 获取用户设置
$settings = $db->querySingle("SELECT * FROM user_settings WHERE id = 1", true);

// 修复：检查设置是否存在
if (!$settings) {
    // 创建默认设置
    $db->exec("INSERT INTO user_settings (id, daily_words) VALUES (1, 20)");
    $settings = ['daily_words' => 20, 'last_study_date' => null, 'last_test_date' => null];
}

// 检查是否需要添加新单词
if ($page == 'study' && (!isset($settings['last_study_date']) || $settings['last_study_date'] != date('Y-m-d'))) {
    // 获取未学习的单词
    $newWords = $db->query("SELECT id FROM vocabulary 
                            WHERE id NOT IN (SELECT word_id FROM learning_progress)
                            ORDER BY RANDOM() 
                            LIMIT " . $settings['daily_words']);
    
    // 添加到学习进度表
    $addedCount = 0;
    while ($word = $newWords->fetchArray()) {
        $nextReview = date('Y-m-d', strtotime("+{$ebbinghaus_intervals[0]} days"));
        $db->exec("INSERT INTO learning_progress (word_id, review_date, next_review_date) 
                   VALUES ({$word['id']}, CURRENT_DATE, '$nextReview')");
        $addedCount++;
    }
    
    // 更新最后学习日期
    $db->exec("UPDATE user_settings SET last_study_date = CURRENT_DATE WHERE id = 1");
}

// 获取今天需要学习的单词
$todayWordsResult = $db->query("SELECT v.id, v.word, v.meaning, lp.stage 
                          FROM vocabulary v
                          JOIN learning_progress lp ON v.id = lp.word_id
                          WHERE lp.next_review_date <= CURRENT_DATE
                          ORDER BY lp.stage ASC, lp.review_date ASC
                          LIMIT " . $settings['daily_words']);
                          
// 将结果转换为数组存储
$todayWordsArray = [];
while ($word = $todayWordsResult->fetchArray()) {
    $todayWordsArray[] = $word;
}

// 获取测试单词
$testWordsResult = $db->query("
    SELECT v.id, v.word, v.meaning 
    FROM (
        -- 今天需要复习的单词
        SELECT v.id, v.word, v.meaning
        FROM vocabulary v
        JOIN learning_progress lp ON v.id = lp.word_id
        WHERE lp.next_review_date <= CURRENT_DATE
        
        UNION
        
        -- 错词（去重）
        SELECT DISTINCT v.id, v.word, v.meaning
        FROM wrong_words w
        JOIN vocabulary v ON w.word_id = v.id
        
        UNION
        
        -- 艾宾浩斯要求重复记忆的单词（阶段小于最高阶段）
        SELECT v.id, v.word, v.meaning
        FROM vocabulary v
        JOIN learning_progress lp ON v.id = lp.word_id
        WHERE lp.stage < " . (count($ebbinghaus_intervals) - 1) . "
    ) v
    ORDER BY RANDOM()
    LIMIT " . ($settings['daily_words'] * 2) . "
");
                         
// 将结果转换为数组存储
$testWordsArray = [];
while ($word = $testWordsResult->fetchArray()) {
    $testWordsArray[] = $word;
}

// 统计词库数量
$totalWords = $db->querySingle("SELECT COUNT(*) FROM vocabulary");

// 统计已掌握单词数量
$masteredWords = $db->querySingle("SELECT COUNT(*) FROM learning_progress WHERE status = 2");

// 计算平均合格率
$testResults = $db->query("SELECT test_count, correct_count FROM learning_progress");
$totalTests = 0;
$totalCorrect = 0;
while ($result = $testResults->fetchArray()) {
    $totalTests += $result['test_count'];
    $totalCorrect += $result['correct_count'];
}
$averageRate = $totalTests > 0 ? round(($totalCorrect / $totalTests) * 100, 2) : 0;

// 获取错词清单
$wrongWordsArray = [];
$wrongWordsResult = $db->query("SELECT v.word, v.meaning, COUNT(w.id) AS error_count 
                          FROM wrong_words w
                          JOIN vocabulary v ON w.word_id = v.id
                          GROUP BY v.id
                          ORDER BY error_count DESC");
while ($word = $wrongWordsResult->fetchArray()) {
    $wrongWordsArray[] = $word;
}

$db->close();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人背单词系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #4e73df;
            --secondary: #858796;
            --success: #1cc88a;
            --info: #36b9cc;
            --warning: #f6c23e;
            --danger: #e74a3b;
            --light: #f8f9fc;
            --dark: #5a5c69;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f7fb;
            color: #333;
            padding-top: 20px;
        }
        
        .app-container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 0.5rem 1.5rem rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .app-header {
            background: linear-gradient(135deg, var(--primary), #2e59d9);
            color: white;
            padding: 20px 0;
            text-align: center;
        }
        
        .app-nav {
            background-color: white;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
        }
        
        .nav-tabs .nav-link {
            padding: 15px 25px;
            font-weight: 600;
            color: var(--dark);
            border: none;
            border-bottom: 3px solid transparent;
        }
        
        .nav-tabs .nav-link.active {
            color: var(--primary);
            border-bottom: 3px solid var(--primary);
            background: transparent;
        }
        
        .app-content {
            padding: 30px;
            min-height: 500px;
        }
        
        .word-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 0.15rem 0.5rem rgba(0,0,0,0.05);
            margin-bottom: 20px;
            overflow: hidden;
            transition: transform 0.3s;
        }
        
        .word-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 0.5rem 1rem rgba(0,0,0,0.1);
        }
        
        .word-header {
            background: var(--primary);
            color: white;
            padding: 15px;
            font-weight: bold;
            cursor: pointer;
        }
        
        .word-body {
            padding: 20px;
            background: var(--light);
            display: none;
        }
        
        .stage-indicator {
            display: inline-block;
            padding: 5px 10px;
            background: var(--info);
            color: white;
            border-radius: 20px;
            font-size: 12px;
            margin-top: 10px;
        }
        
        .btn-test {
            background: var(--success);
            color: white;
            font-weight: bold;
            padding: 12px 30px;
            border-radius: 50px;
            font-size: 18px;
            box-shadow: 0 4px 6px rgba(28, 200, 138, 0.3);
            transition: all 0.3s;
        }
        
        .btn-test:hover {
            background: #17a673;
            transform: translateY(-2px);
            box-shadow: 0 6px 10px rgba(28, 200, 138, 0.4);
        }
        
        .stat-card {
            text-align: center;
            padding: 25px 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            color: white;
            box-shadow: 0 0.15rem 0.5rem rgba(0,0,0,0.1);
        }
        
        .stat-card.total {
            background: linear-gradient(135deg, var(--primary), #2e59d9);
        }
        
        .stat-card.mastered {
            background: linear-gradient(135deg, var(--success), #17a673);
        }
        
        .stat-card.rate {
            background: linear-gradient(135deg, var(--info), #2c9faf);
        }
        
        .stat-card .number {
            font-size: 32px;
            font-weight: bold;
            margin: 10px 0;
        }
        
        .test-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 0.15rem 0.5rem rgba(0,0,0,0.05);
            transition: all 0.3s;
        }
        
        .test-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 0.5rem 1rem rgba(0,0,0,0.1);
        }
        
        .test-card-header {
            background: var(--primary);
            color: white;
            padding: 15px;
            border-radius: 8px 8px 0 0;
            margin: -20px -20px 20px -20px;
        }
        
        .test-options .form-check {
            margin: 10px 0;
        }
        
        .wrong-word-item {
            padding: 10px 15px;
            border-bottom: 1px solid #eee;
        }
        
        .wrong-word-item:last-child {
            border-bottom: none;
        }
        
        .error-count {
            background: var(--danger);
            color: white;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            margin-right: 10px;
        }
        
        .a4-page {
            width: 210mm;
            min-height: 297mm;
            margin: 0 auto;
            padding: 20mm;
            background: white;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        
        .print-header {
            text-align: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #333;
        }
        
        .print-word {
            padding: 10px;
            border-bottom: 1px solid #eee;
        }
        
        @media print {
            body * {
                visibility: hidden;
            }
            .a4-page, .a4-page * {
                visibility: visible;
            }
            .a4-page {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                padding: 0;
                margin: 0;
                box-shadow: none;
            }
            .print-button {
                display: none;
            }
        }
        
        .progress-container {
            height: 8px;
            background: #e9ecef;
            border-radius: 4px;
            overflow: hidden;
            margin: 20px 0;
        }
        
        .progress-bar {
            height: 100%;
            background: var(--primary);
            border-radius: 4px;
            transition: width 0.5s ease;
        }
        
        .empty-state {
            text-align: center;
            padding: 40px 20px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 0.15rem 0.5rem rgba(0,0,0,0.05);
        }
        
        .empty-state-icon {
            font-size: 64px;
            color: var(--info);
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="app-container">
        <div class="app-header">
            <h1><i class="fas fa-book-open me-2"></i>个人背单词系统</h1>
            <p class="mb-0">基于艾宾浩斯记忆法的智能单词学习工具</p>
        </div>
        
        <div class="app-nav">
            <ul class="nav nav-tabs justify-content-center" id="navTabs">
                <li class="nav-item">
                    <a class="nav-link <?= $page == 'study' ? 'active' : '' ?>" 
                       href="?page=study">学习</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?= $page == 'test' ? 'active' : '' ?>" 
                       href="?page=test">测试</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?= $page == 'statistics' ? 'active' : '' ?>" 
                       href="?page=statistics">统计</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?= $page == 'settings' ? 'active' : '' ?>" 
                       href="?page=settings">设置</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?= $page == 'wrong_words' ? 'active' : '' ?>" 
                       href="?page=wrong_words">错词本</a>
                </li>
            </ul>
        </div>
        
        <div class="app-content">
            <?php if ($page == 'study'): ?>
                <!-- 学习模块 -->
                <h2 class="mb-4"><i class="fas fa-graduation-cap me-2"></i>今日学习</h2>
                
                <div class="progress-container">
                    <div class="progress-bar" id="progressBar" style="width: 0%"></div>
                </div>
                
                <div class="row" id="wordList">
                    <?php 
                    $wordCount = 0;
                    foreach ($todayWordsArray as $word): 
                        $wordCount++;
                    ?>
                    <div class="col-md-6 col-lg-4 mb-4">
                        <div class="word-card">
                            <div class="word-header" onclick="flipCard(this)">
                                <?= htmlspecialchars($word['word']) ?>
                                <div class="stage-indicator">阶段 <?= $word['stage'] + 1 ?></div>
                            </div>
                            <div class="word-body">
                                <p class="mb-0"><?= htmlspecialchars($word['meaning']) ?></p>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    
                    <?php if ($wordCount == 0): ?>
                    <div class="col-12">
                        <div class="empty-state">
                            <div class="empty-state-icon">
                                <i class="fas fa-check-circle"></i>
                            </div>
                            <h3>恭喜！</h3>
                            <p class="mb-0">今天没有需要学习的单词，休息一下吧！</p>
                            <p class="mt-3">
                                <a href="?page=settings" class="btn btn-primary">
                                    <i class="fas fa-file-import me-2"></i>导入更多单词
                                </a>
                            </p>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <?php if ($wordCount > 0): ?>
                <div class="text-center mt-4">
                    <a href="?page=test" class="btn btn-test">
                        <i class="fas fa-pencil-alt me-2"></i>开始测试
                    </a>
                </div>
                <?php endif; ?>
                
            <?php elseif ($page == 'test'): ?>
                <!-- 测试模块 - 添加每日测试限制 -->
                <h2 class="mb-4"><i class="fas fa-pencil-alt me-2"></i>单词测试</h2>
                
                <?php if (isset($settings['last_test_date']) && $settings['last_test_date'] == date('Y-m-d')): ?>
                <div class="alert alert-info text-center py-5">
                    <h4><i class="fas fa-info-circle me-2"></i>今日已测试</h4>
                    <p class="mb-0">您今天已经完成过测试，请明天再来！</p>
                    <p class="mt-3">
                        <a href="?page=statistics" class="btn btn-primary">
                            <i class="fas fa-chart-bar me-2"></i>查看统计
                        </a>
                    </p>
                </div>
                <?php else: ?>
                <form method="post">
                    <?php 
                    $testCount = 0;
                    foreach ($testWordsArray as $word): 
                        $testCount++;
                        
                        // 生成错误选项
                        $wrongOptions = [];
                        $db = init_db();
                        $wrongWords = $db->query("SELECT meaning FROM vocabulary 
                                                WHERE id != {$word['id']} 
                                                ORDER BY RANDOM() LIMIT 3");
                        while ($wrong = $wrongWords->fetchArray()) {
                            $wrongOptions[] = $wrong['meaning'];
                        }
                        $db->close();
                        
                        // 合并选项并打乱顺序
                        $options = array_merge([$word['meaning']], $wrongOptions);
                        shuffle($options);
                    ?>
                    <div class="test-card">
                        <div class="test-card-header">
                            <h4 class="mb-4"><?= $testCount ?>. <?= htmlspecialchars($word['word']) ?></h4>
                        </div>
                        <div class="test-options">
                            <?php foreach ($options as $index => $option): ?>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" 
                                       name="answers[<?= $word['id'] ?>]" 
                                       id="option<?= $word['id'] ?>-<?= $index ?>" 
                                       value="<?= htmlspecialchars($option) ?>" required>
                                <label class="form-check-label" for="option<?= $word['id'] ?>-<?= $index ?>">
                                    <?= htmlspecialchars($option) ?>
                                </label>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    
                    <?php if ($testCount > 0): ?>
                    <div class="text-center mt-4">
                        <button type="submit" name="test_submit" class="btn btn-primary btn-lg">
                            <i class="fas fa-paper-plane me-2"></i>提交答案
                        </button>
                    </div>
                    <?php else: ?>
                    <div class="alert alert-info text-center py-4">
                        <h4><i class="fas fa-info-circle me-2"></i>没有测试内容</h4>
                        <p class="mb-0">今天没有需要测试的单词，请先学习新单词。</p>
                    </div>
                    <?php endif; ?>
                </form>
                <?php endif; ?>
                
            <?php elseif ($page == 'statistics'): ?>
                <!-- 统计模块 -->
                <h2 class="mb-4"><i class="fas fa-chart-bar me-2"></i>学习统计</h2>
                
                <div class="row mb-5">
                    <div class="col-md-4">
                        <div class="stat-card total">
                            <i class="fas fa-book fa-3x mb-3"></i>
                            <h3>词库总量</h3>
                            <div class="number"><?= $totalWords ?></div>
                            <p>已收录单词数量</p>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="stat-card mastered">
                            <i class="fas fa-check-circle fa-3x mb-3"></i>
                            <h3>已掌握单词</h3>
                            <div class="number"><?= $masteredWords ?></div>
                            <p>完成记忆的单词</p>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="stat-card rate">
                            <i class="fas fa-percent fa-3x mb-3"></i>
                            <h3>平均合格率</h3>
                            <div class="number"><?= $averageRate ?>%</div>
                            <p>测试正确率</p>
                        </div>
                    </div>
                </div>
                
                <div class="card mb-4">
                    <div class="card-header bg-white">
                        <h5 class="mb-0"><i class="fas fa-history me-2"></i>学习进度</h5>
                    </div>
                    <div class="card-body">
                        <div class="progress-container">
                            <div class="progress-bar" style="width: <?= $totalWords ? round(($masteredWords / $totalWords) * 100) : 0 ?>%"></div>
                        </div>
                        <div class="d-flex justify-content-between mt-2">
                            <span>0%</span>
                            <span>50%</span>
                            <span>100%</span>
                        </div>
                        <div class="text-center mt-3">
                            <span class="badge bg-primary">已掌握 <?= $masteredWords ?>/<?= $totalWords ?> 单词</span>
                        </div>
                    </div>
                </div>
                
                <div class="text-center mt-4">
                    <a href="?page=wrong_words" class="btn btn-primary">
                        <i class="fas fa-print me-2"></i>查看错词本
                    </a>
                </div>
                
            <?php elseif ($page == 'settings'): ?>
                <!-- 设置模块 - 添加清除现有词库选项 -->
                <h2 class="mb-4"><i class="fas fa-cog me-2"></i>系统设置</h2>
                
                <form method="post" enctype="multipart/form-data">
                    <div class="card mb-4">
                        <div class="card-header bg-white">
                            <h5 class="mb-0"><i class="fas fa-sliders-h me-2"></i>学习设置</h5>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label class="form-label">每日学习单词数量</label>
                                <input type="number" name="daily_words" class="form-control" 
                                       value="<?= $settings['daily_words'] ?>" min="5" max="100">
                            </div>
                        </div>
                    </div>
                    
                    <div class="card mb-4">
                        <div class="card-header bg-white">
                            <h5 class="mb-0"><i class="fas fa-file-import me-2"></i>导入词库</h5>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label class="form-label">选择词库文件</label>
                                <input type="file" name="vocab_file" class="form-control" accept=".txt">
                                <div class="form-text">
                                    文件格式：每行一个单词，格式为"单词,释义"（例如：apple,苹果）
                                </div>
                            </div>
                            <div class="form-check mb-3">
                                <input class="form-check-input" type="checkbox" name="clear_existing" id="clear_existing">
                                <label class="form-check-label" for="clear_existing">
                                    清除现有词库后再导入
                                </label>
                            </div>
                        </div>
                    </div>
                    
                    <div class="text-center mt-4">
                        <button type="submit" class="btn btn-primary btn-lg">
                            <i class="fas fa-save me-2"></i>保存设置
                        </button>
                    </div>
                </form>
                
            <?php elseif ($page == 'wrong_words'): ?>
                <!-- 错词本模块 -->
                <h2 class="mb-4"><i class="fas fa-exclamation-triangle me-2"></i>错词本</h2>
                
                <?php if (!empty($wrongWordsArray)): ?>
                <div class="card mb-4">
                    <div class="card-header bg-white d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">错词清单</h5>
                        <a href="?page=wrong_words_print" class="btn btn-sm btn-primary">
                            <i class="fas fa-print me-1"></i>打印
                        </a>
                    </div>
                    <div class="card-body p-0">
                        <div class="list-group list-group-flush">
                            <?php foreach ($wrongWordsArray as $word): ?>
                            <div class="list-group-item wrong-word-item">
                                <span class="error-count"><?= $word['error_count'] ?></span>
                                <strong><?= htmlspecialchars($word['word']) ?></strong> - 
                                <?= htmlspecialchars($word['meaning']) ?>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                <?php else: ?>
                <div class="empty-state">
                    <div class="empty-state-icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <h3>太棒了！</h3>
                    <p class="mb-0">目前还没有错词记录，继续保持！</p>
                </div>
                <?php endif; ?>
                
            <?php elseif ($page == 'wrong_words_print'): ?>
                <!-- 错词打印模块 -->
                <div class="a4-page">
                    <div class="print-header">
                        <h2>错词清单</h2>
                        <p>生成日期: <?= date('Y年m月d日') ?></p>
                    </div>
                    
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th width="10%">错误次数</th>
                                <th width="30%">单词</th>
                                <th width="60%">释义</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($wrongWordsArray as $word): ?>
                            <tr>
                                <td class="text-center"><?= $word['error_count'] ?></td>
                                <td><?= htmlspecialchars($word['word']) ?></td>
                                <td><?= htmlspecialchars($word['meaning']) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    
                    <div class="text-center mt-4 print-button">
                        <button onclick="window.print()" class="btn btn-primary">
                            <i class="fas fa-print me-2"></i>打印错词本
                        </button>
                        <a href="?page=wrong_words" class="btn btn-secondary ms-2">
                            <i class="fas fa-arrow-left me-2"></i>返回
                        </a>
                    </div>
                </div>
            <?php endif; ?>
        </div>
        
        <div class="app-footer text-center py-3 bg-light">
            <p class="mb-0">个人背单词系统 &copy; <?= date('Y') ?></p>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 卡片翻转效果
        function flipCard(element) {
            const card = $(element).closest('.word-card');
            const body = card.find('.word-body');
            
            if (body.is(':visible')) {
                body.slideUp();
            } else {
                body.slideDown();
            }
        }
        
        // 初始化学习进度条
        $(document).ready(function() {
            const totalWords = <?= count($todayWordsArray) ?>;
            let viewedWords = 0;
            
            // 更新进度条
            function updateProgress() {
                const progress = Math.min(Math.round((viewedWords / totalWords) * 100), 100);
                $('#progressBar').css('width', progress + '%');
            }
            
            // 点击卡片标记为已查看
            $('.word-header').click(function() {
                if (!$(this).hasClass('viewed')) {
                    $(this).addClass('viewed');
                    viewedWords++;
                    updateProgress();
                }
            });
            
            // 初始更新进度条
            updateProgress();
        });
    </script>
</body>
</html>